﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using CounterServerModel;
using System.Data;


namespace SmartCounters
{
	public partial class FaultReport : System.Web.UI.Page
	{
		int m_CurrentLoggedOnUserID;
		DataTable m_userAccountsTable;

		protected void Page_Load(object sender, EventArgs e)
		{
			((MainTemplate)Master).m_PagePermissionFilter = MainTemplate.k_UserPageFilter;
		}

		protected void Page_Prerender(object sender, EventArgs e)
		{
			InformationReader infoProvider = new InformationReader();
			m_CurrentLoggedOnUserID = ((MainTemplate)Master).LoggedInUser.ID;
			
			SetUsersAccounts();

			if (!IsPostBack)
			{
				bindDropDownListData();
			}
		}

		protected void ReportFault(object sender, EventArgs e)
		{
			string faultDescritpion = tbFaultdescription.Text;
            int AccountID = int.Parse(ddAccounts.SelectedItem.Value);

			InformationUpdater updateProvider = new InformationUpdater();
			updateProvider.CreateFault(((MainTemplate)Master).AuthenticatedLoggedInUserCredentials, AccountID, faultDescritpion);

			tbFaultdescription.Text = "";
			ddAccounts.ClearSelection();
			lblStatusMessage.Text = "Fault Sent! Thank you for letting us know ...";
		}

		private void bindDropDownListData()
		{
			foreach (DataRow account in m_userAccountsTable.Rows)
			{
				string accountLable = account["Country"] + " " + account["City"] + " " + account["street"] + " " + account["House"] + "/" + account["Apartment"];
				ddAccounts.Items.Add(new ListItem(accountLable, account["AccountID"].ToString()));
			}
		}

		private void SetUsersAccounts()
		{
			// If Admin Show all Accounts else show only associated accounts
			if (m_CurrentLoggedOnUserID == 1)
			{
				m_userAccountsTable = new InformationReader().GetAccountsDataTable(((MainTemplate)Master).AuthenticatedLoggedInUserCredentials);
			}
			else
			{
				m_userAccountsTable = new InformationReader().GetUserAssociatedAccounts(((MainTemplate)Master).AuthenticatedLoggedInUserCredentials, m_CurrentLoggedOnUserID);
			}
		}

	}
}